package com.karrim.server.io;

import com.google.inject.Inject;
import com.karrim.server.util.Util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author andrea.cantafio
 */
public class JClassLoader extends ClassLoader {

    public interface Reloadable {
    }

    @Inject
    public JClassLoader() {
        super();
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            FileInputStream target = new FileInputStream(Util.ABS_PATH_CLASSES + Util.FILE_DELIMITER + name.replace('.', Util.FILE_DELIMITER) + ".class");
            byte[] b = new byte[target.available()];
            return defineClass(name, b, 0, b.length);
        } catch (IOException ex) {
            Logger.getLogger(JClassLoader.class.getName()).log(Level.SEVERE, null, ex);
            throw new ClassNotFoundException();
        }
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class clazz = findLoadedClass(name);
        if (clazz == null) {
            try {
                return super.loadClass(name, resolve);
            } catch (ClassNotFoundException cnfe) {
                return findClass(name);
            }
        }
        return clazz;
    }
}
